#include <stdio.h>
#include <stdlib.h>
struct linknode
{
	int data;
	struct linknode *next;
};

//初始化链表
void init_linknode()
{
	//创建头节点
	struct linknode *head;
	head=malloc(sizeof(struct linknode));
	head->data=0;
	head->next=NULL;
	
	struct linknode *p=head;
	//创建新结点
	int val;
	while(val!=0)
	{
		printf("插入数据：");
		scanf("%d",&val);
		if(val==0)break;
		struct linknode *new=malloc(sizeof(struct linknode));
		new->data=val;
		new->next=NULL;
		
		//新结点插入链表中
		p->next=new;
		
		//更新尾部指针指向
		p=new;
	}
	
}

//遍历
void foreach_linknode(struct linknode *head)
{
	struct linknode *ph=head->next;
	while(ph!=NULL)
	{
		printf("%d\n",ph->data);
		ph=ph->next;
	}
}

//插入：在oldval前面插入newval
void insortbyvalue_linknode(struct linknode *head,int oldvalue,int newvalue)
{
	if(head==NULL)
	{
		
	}
	//定义两个指针变量
	struct linknode *pprev=head,*pcurrent=pprev->next;
	while(pcurrent!=NULL)
	{
		if(pcurrent->data==oldvalue)break;
		pprev=pcurrent;
		pcurrent=pcurrent->next;
	}
	//如果pcurrent为NULL，说明链表中不存在oldvalue
	if(pcurrent==NULL)return;
	
	//创建结点,并连接
	struct linknode *newnode=malloc(sizeof(struct linknode));
	newnode->data=newvalue;
	newnode->next=pcurrent;
	pprev->next=newnode;
}

//清空结点
void clear_linklist(struct linknode *head)
{
	//辅助指针变量
	struct linknode *pcurrent=head->next;
	while(pcurrent!=NULL)
	{
		//保存下一个结点的地址
		struct linknode *pnext=pcurrent->next;
		//释放当前结点内存
		free(pcurrent);
		//指向下一个结点
		pcurrent=pnext;
	}
	head->next=NULL;
}

//删除值为val的结点
void removebyvalue_linknode(struct linknode *head,int val)
{
	//两个辅助指针变量
	struct linknode *pprev=head,*pcurrent=pprev->next;
	while(pcurrent!=NULL)
	{
		//移动两个辅助指针
		if(pcurrent->data==val)break;
		pprev=pcurrent;
		pcurrent=pcurrent->next;
	}
	if(pcurrent==NULL)return;
	pprev->next=pcurrent->next;
	free(pcurrent);
	pcurrent=NULL;
}

//销毁链表
void destroy_linklist(struct linknode *head)
{
	if(NULL==head)return;
	struct linknode *pcurrent=head;
	while(pcurrent!=NULL)
	{
		//保存下一个结点位置
		struct linknode *pnext=pcurrent->next;
		
		//释放当前结点
		free(pcurrent);
		
		pcurrent=pnext;
	}
}

int main()
{
	
	struct linknode *head;
	head=malloc(sizeof(struct linknode));
	head->data=0;
	head->next=NULL;
	
	struct linknode *p=head;
	//创建新结点
	int val=-1;
	while(val!=0)
		{
			printf("插入数据：");
			scanf("%d",&val);
			if(val==0)break;
			struct linknode *new=malloc(sizeof(struct linknode));
			new->data=val;
			new->next=NULL;
			
			//新结点插入链表中
			p->next=new;
			
			//更新尾部指针指向
			p=new;
		}
	void insortbyvalue_linknode(struct linknode *head,int oldvalue,int newvalue);
	insortbyvalue_linknode(head,40,35);
	void removebyvalue_linknode(struct linknode *head,int val);
	removebyvalue_linknode(head,20);
	void clear_linklist(struct linknode *head);
	clear_linklist(head);
	struct linknode *ph=head->next;
	
	while(ph!=NULL)
		{
			printf("%d\n",ph->data);
			ph=ph->next;
		}
	

	return 0;
}